package com.cooba.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.bean.GameBean;
import com.cooba.bean.VideoBeans;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/14.
 * 网络监听工具类
 */
public class CommonUtil {
    private static String appId;
    private static String mGameName = null;
    private static DownloadManager downloadManager;
    private static Map<Long, String> mIdMap = new HashMap<Long, String>();
    private static Map<String, TextView> mTextViewMap = new HashMap<String, TextView>();
    private static Map<String, String> mGameMap = new HashMap<>();

    //判断是否有网络
    public static boolean isNetWork(Context context) {
        //得到网络的管理者
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
     *
     * @param context
     * @return
     */
    public static int isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return 0;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetworkInfo netWorkInfo = info[i];
                        if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            String extraInfo = netWorkInfo.getExtraInfo();
                            if ("cmwap".equalsIgnoreCase(extraInfo) || "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
                                return 2;
                            }
                            return 3;
                        }
                    }
                }
            }
        }
        return 0;
    }

    //获取地理位置
    public static String getLocation(Context context, int flag) {

        String latitude ="0.0";
        String longitude = "0.0";

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                latitude = new java.text.DecimalFormat("#.00").format(location.getLatitude());     //经度
                longitude = new java.text.DecimalFormat("#.00").format(location.getLongitude()); //纬度
            }
        } else {
//            LocationListener locationListener = new LocationListener() {
//
//                // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
//                @Override
//                public void onStatusChanged(String provider, int status, Bundle extras) {
//
//                }
//
//                // Provider被enable时触发此函数，比如GPS被打开
//                @Override
//                public void onProviderEnabled(String provider) {
//
//                }
//
//                // Provider被disable时触发此函数，比如GPS被关闭
//                @Override
//                public void onProviderDisabled(String provider) {
//
//                }
//
//                //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
//                @Override
//                public void onLocationChanged(Location location) {
//                    if (location != null) {
//                        Log.e("Map", "Location changed : Lat: "
//                                + location.getLatitude() + " Lng: "
//                                + location.getLongitude());
//                    }
//                }
//            };
//            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                latitude = new java.text.DecimalFormat("#.00").format(location.getLatitude());     //经度
                longitude = new java.text.DecimalFormat("#.00").format(location.getLongitude()); //纬度
            }

        }
        if (flag == 1) {
            return longitude;
        } else {
            return latitude;
        }

    }

    /**
     * 获取手机mac地址
     * 错误返回12个0
     */
    public static String getMacAddress(Context context) {
        // 获取mac地址：
        String macAddress = "00:00:00:00:00:00";
        try {
            WifiManager wifiMgr = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr
                    .getConnectionInfo());
            if (null != info) {
                if (!TextUtils.isEmpty(info.getMacAddress()))
                    macAddress = info.getMacAddress();
                else
                    return macAddress;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return macAddress;
        }
        return macAddress;
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {

        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } else {
            return null;
        }
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd HH:mm:ss
     */

    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getScreenPicHeight(int screenWidth, Bitmap bitmap) {
        int picWidth = bitmap.getWidth();
        int picHeight = bitmap.getHeight();
        int picScreenHeight = 0;
        picScreenHeight = (screenWidth * picHeight) / picWidth;
        return picScreenHeight;
    }

    /**
     * 写， 读sdcard目录上的文件，要用FileOutputStream， 不能用openFileOutput
     * 不同点：openFileOutput是在raw里编译过的，FileOutputStream是任何文件都可以
     *
     * @param fileName
     * @param message
     */
    // 写在/mnt/sdcard/目录下面的文件
    public void writeFileSdcard(String fileName, String message) {

        try {

            // FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

            FileOutputStream fout = new FileOutputStream(fileName);

            byte[] bytes = message.getBytes();

            fout.write(bytes);

            fout.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    // 读在/mnt/sdcard/目录下面的文件

    public static String readFileSdcard() {
        String filePath = "/sdcard/Cooba/";
        String fileName = "bannerinfo.txt";
        String res = "";

        try {
            File file = new File(filePath + fileName);
            if (file.exists()) {
                FileInputStream fin = new FileInputStream(filePath + fileName);

                int length = fin.available();

                byte[] buffer = new byte[length];

                fin.read(buffer);

                res = EncodingUtils.getString(buffer, "UTF-8");

                fin.close();
            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        Log.d("wei", res.toString());
        return res;

    }


    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent) {
        String filePath = "/sdcard/Cooba/";
        String fileName = "bannerinfo.txt";
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + ",";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    //删除文件
    public static void deleteFile() {
        String filePath = "/sdcard/Cooba/";
        String fileName = "bannerinfo.txt";
        File file = null;
        file = new File(filePath + fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    public static void putTextViewMap(String id, TextView tv) {
        mTextViewMap.put(id, tv);
    }

    public static TextView getTextViewById(String id) {
        return mTextViewMap.get(id);
    }

    public static void putGameId(String packagename, String gameId) {
        mGameMap.put(packagename, gameId);
    }

    public static String getGameId(String packagename) {
        return mGameMap.get(packagename);
    }


    public static void installAPK(Context context, File file) {
        if (file.exists()) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            ((ContextWrapper) context).startActivity(i);
        } else {
            Toast.makeText(context, "安装文件不存在!", Toast.LENGTH_SHORT).show();
        }
    }

    public static void downloadAPK(final Context context, final GameBean.GameInfo gameInfo) {

        HttpUtils httpUtils = new HttpUtils();
        final String apkFilePath = new StringBuilder(Environment
                .getExternalStorageDirectory().getAbsolutePath())
                .append(File.separator).append(Constants.DOWN_DIR)
                .append(File.separator).append(gameInfo.getGame_name() + ".apk")
                .toString();
        final File file = new File(apkFilePath);
        if (file.exists()) {
            file.delete();
        }
        String url=gameInfo.getGame_android_apk();
        httpUtils.download(url, apkFilePath, true, false, new RequestCallBack<File>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                Log.d("wei", "current" + current + "total" + total);
//                TextView tv=CommonUtil.getTextViewById(gameInfo.getId());
//                tv.setText((int) (current * 100 / total) + "%");
                int progress = (int) (current * 100 / total);
                gameInfo.setDownload_status(1);
                gameInfo.setProgress(progress);
                Intent intent = new Intent(Constants.ACTION_UPDATE_DOWNLOAD_PROGRESS);
                //intent.putExtra("Progress", progress);
                intent.putExtra("download_data", gameInfo);
                context.sendBroadcast(intent);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                //安装app
                File file = new File(apkFilePath);
                String packagename = getApkFilePackage(context, file);
                putGameId(packagename, gameInfo.getId());
                Log.d("wei", "包名:" + packagename);
                installAPK(context, file);
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    public static void getVantager(final Context context, String gameId) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        String user_id = SharedPreferencesUtil.getData(context, "login_id", "");
        String user_name = SharedPreferencesUtil.getData(context, "name", "");
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("user_id", user_id);
        params.addBodyParameter("user_name", user_name);
        params.addBodyParameter("game_id", gameId);
        params.addBodyParameter("date", date);
        String url = ServerURL.httpUrl + ServerURL.gameDownload;
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", "上传积分成功:" + responseInfo.result);
                String msg = JSON.parseObject(responseInfo.result).getString("msg");
                String status = JSON.parseObject(responseInfo.result).getString("status");

                if (status.equals("1")) {
                    String download_integral = JSON.parseObject(responseInfo.result).getString("vantager");
//                    String original_integral = SharedPreferencesUtil.getData(context, "allTotalIntegral", "");
//                    int total = Integer.parseInt(download_integral) + Integer.parseInt(original_integral);
//                    SharedPreferencesUtil.saveData(context, "allTotalIntegral", String.valueOf(total));
                    Intent intent = new Intent(Constants.UPDATE_DATA);
                    context.sendBroadcast(intent);
                    Toast.makeText(context, "获取积分成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei", "上传积分失败:");
            }
        });
    }


    public static String getApkFilePackage(Context context, File apkFile) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkFile.getPath(), PackageManager.GET_ACTIVITIES);
        if (info != null) {
            return info.applicationInfo.packageName;
        }
        return null;
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        if (packages != null) {
            for (PackageInfo packageInfo : packages) {
                if (packageInfo.packageName.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *
     * 观看记录
     *
     *
     */
    //保存
    public static void setVideoHistoryList(Context context,List<VideoBeans.VideoListEntity> datalist) {
        SharedPreferences sp=context.getSharedPreferences("video_history_data", Context.MODE_PRIVATE);
        if (null == datalist|| datalist.size() <= 0)
            return;

        Gson gson = new Gson();
        String strJson = gson.toJson(datalist);
        sp.edit().putString("history",strJson).commit();
    }


    //获取
    public static List<VideoBeans.VideoListEntity> getVideoHistoryList(Context context) {
        SharedPreferences sp=context.getSharedPreferences("video_history_data",Context.MODE_PRIVATE);
        String strJson = sp.getString("history", null);
        if (null == strJson) {
            return null;
        }
        Gson gson = new Gson();
        List<VideoBeans.VideoListEntity> datalist= gson.fromJson(strJson,
                new TypeToken<List<VideoBeans.VideoListEntity>>() {
                }.getType());
        return datalist;
    }
    public static void removeVideoHistory(Context context){
        SharedPreferences sp=context.getSharedPreferences("video_history_data",Context.MODE_PRIVATE);
        sp.edit().clear().commit();
    }

}
